﻿using CommonLib;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using YouErYuanBLL;
using YouErYuanManage.Models;
using YouErYuanModels;

namespace YouErYuanManage.Controllers
{
    public class VideoSettingController : Controller
    {
        // GET: VideoSetting
        //public ActionResult Index()
        //{
        //    return View();
        //}

        //分页，获取幼儿园视频列表
        [YouErYuanManage.Filter.IsLogin]
        public string VideoSettingPageList()
        {
            VideoSettingBLL ckbll = new VideoSettingBLL();
            int pageIndex = 0;
            int pageSize = 0;
            try
            {
                pageIndex = Convert.ToInt32(Request["pageIndex"]);
                pageSize = Convert.ToInt32(Request["pageSize"]);
            }
            catch (Exception)
            {
                pageIndex = 1;
                pageSize = 10;
            }
            string schoolid = (HttpContext.Session["user"] as Teacher).Schoolid;
            int total = 0;
            object dt = ckbll.VideoSettingPageList(pageIndex, pageSize, schoolid, out total);
            int pageCount = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;//总页数
            var data = new
            {
                pageIndex = pageIndex,
                pageCount = pageCount,
                list = dt,
                total = total
            };
            return CommonMethod.FormatJsonObj("", data);
        }
        //分页，获取幼儿园视频设备信息
        [YouErYuanManage.Filter.IsLogin]
        public string VideoInfo()
        {
            VideoSettingBLL ckbll = new VideoSettingBLL();
            string videId = Request["videId"];
            object dt = ckbll.VideoInfo(videId);
            return CommonMethod.FormatJsonObj("", dt);
        }

        //修改幼儿园视频设备信息
        [YouErYuanManage.Filter.IsLogin]
        public string UpdateVideo(VideoLive model)
        {
            VideoSettingBLL ckbll = new VideoSettingBLL();
            Teacher teacherModel = Session["user"] as Teacher;
            model.schoolId = teacherModel.Schoolid;
            if (string.IsNullOrEmpty(model.id) || string.IsNullOrWhiteSpace(model.id))
            {
                return CommonMethod.FormatJsonObj("", "记录主键不能为空");
            }
            if (string.IsNullOrEmpty(model.deviceSerialNo) || string.IsNullOrWhiteSpace(model.deviceSerialNo))
            {
                return CommonMethod.FormatJsonObj(3);//摄像头序列号必填
            }
            if (string.IsNullOrEmpty(model.schoolId) || string.IsNullOrWhiteSpace(model.schoolId))
            {
                return CommonMethod.FormatJsonObj("", "schoolId不能为空");
            }
            //查询原始数据
            VideoLive oldInfo = ckbll.GetVideoLive(model.id);
            if (!oldInfo.deviceSerialNo.Equals(model.deviceSerialNo))
            {
                //检查摄像头序列号唯一
                int count = ckbll.CheckDeviceSerialNo(model.deviceSerialNo, model.schoolId);
                if (count == 1)
                {
                    return CommonMethod.FormatJsonObj(2);//此摄像头序列号已存在
                }
            }
            //获取封面图片、直播地址
            //VideoLive ysInfo = GetVideoInfo(model.deviceSerialNo);
            //model.videoURL = ysInfo.videoURL;
            //model.coverImgURL = ysInfo.coverImgURL;
            object efcount = ckbll.UpdateVideo(model);
            return CommonMethod.FormatJsonObj(efcount);
        }

        [YouErYuanManage.Filter.IsLogin]
        public string SelectClass()
        {
            VideoSettingBLL tbll = new VideoSettingBLL();
            string schoolid = (HttpContext.Session["user"] as Teacher).Schoolid;
            object o = tbll.SelectClassForSchoolid(schoolid);
            return CommonLib.CommonMethod.FormatJsonObj("", o);
        }

        /// <summary>
        /// 新增摄像头
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [YouErYuanManage.Filter.IsLogin]
        public string Insert(VideoLive model)
        {
            VideoSettingBLL vsbll = new VideoSettingBLL();
            Teacher teacherModel = Session["user"] as Teacher;
            model.schoolId = teacherModel.Schoolid;
            if (string.IsNullOrEmpty(model.videoTitle) == false && string.IsNullOrWhiteSpace(model.videoTitle) == false)
            {
                if (model.videoTitle.Length > 100)
                {
                    return CommonMethod.FormatJsonObj("", "标题不能超过100个字符");
                }
            }
            if (string.IsNullOrEmpty(model.schoolId) || string.IsNullOrWhiteSpace(model.schoolId))
            {
                return CommonMethod.FormatJsonObj("", "schoolId不能为空");
            }
            if (string.IsNullOrEmpty(model.deviceSerialNo) || string.IsNullOrWhiteSpace(model.deviceSerialNo))
            {
                return CommonMethod.FormatJsonObj(3);//摄像头序列号必填
            }
            //检查摄像头序列号唯一
            int count = vsbll.CheckDeviceSerialNo(model.deviceSerialNo, model.schoolId);
            if (count == 1)
            {
                return CommonMethod.FormatJsonObj(2);//此摄像头序列号已存在
            }
            //获取封面图片、直播地址
            //VideoLive ysInfo = GetVideoInfo(model.deviceSerialNo);
            //model.videoURL = ysInfo.videoURL;
            //model.coverImgURL = ysInfo.coverImgURL;
            int efcount = vsbll.InsertVideo(model);
            return CommonMethod.FormatJsonObj(efcount);
        }

        [YouErYuanManage.Filter.IsLogin]
        public string DeleteVideo(string videoId)
        {
            int count = new VideoSettingBLL().DeleteVideo(videoId);
            return CommonMethod.FormatJsonObj(count);
        }

        /// <summary>
        /// 获取当前序列号摄像头的信息
        /// </summary>
        /// <returns></returns>
        public VideoLive GetVideoInfo(string xulieNo)
        {
            //app配置信息
            string appKey = System.Configuration.ConfigurationManager.AppSettings["appKey"];
            string secret = System.Configuration.ConfigurationManager.AppSettings["secret"];
            string phone = System.Configuration.ConfigurationManager.AppSettings["phone"];

            string backTxt = "";
            //获取萤石云平台系统时间
            string urlTime = "https://open.ys7.com/api/time/get?id=1&appKey=" + appKey;
            string serverTimeJson = RequestWebAPI(urlTime, "");
            Result obj = JsonConvert.DeserializeObject<Result>(serverTimeJson);
            ResultData resultdata = JsonConvert.DeserializeObject<ResultData>(obj.result.ToString());
            YSTime ystime = JsonConvert.DeserializeObject<YSTime>(resultdata.data.ToString());
            string serverTime = ystime.serverTime;//服务器时间戳          

            string accessTokenJson = GetAccessToken(serverTime, phone, appKey, secret);
            Result obj2 = JsonConvert.DeserializeObject<Result>(accessTokenJson);
            ResultData resultdata2 = JsonConvert.DeserializeObject<ResultData>(obj2.result.ToString());
            AccessToken accessTokenData = JsonConvert.DeserializeObject<AccessToken>(resultdata2.data.ToString());
            string accessToken = accessTokenData.accessToken;

            backTxt = SquareVideoListByUser(backTxt, serverTime, appKey, secret);
            Result result = JsonConvert.DeserializeObject<Result>(backTxt);
            string json = result.result.ToString();
            ResultInfo resultinfo = JsonConvert.DeserializeObject<ResultInfo>(json);
            //string xulieNo = "542685408";//摄像头序列号
            string m3u9Url = string.Empty;//需要的摄像头直播地址
            string squareId = string.Empty;
            foreach (VideoInfo item in resultinfo.data)
            {
                if (item.m3u8Url.Contains(xulieNo))
                {
                    m3u9Url = item.m3u8Url;
                    squareId = item.squareId;
                    break;
                }
            }
            //解析图片路径    //squareId=643000          
            string url = "http://square.ys7.com/play/index?cameraId=" + squareId;
            string html = RequestWebAPI(url, "");
            int startIndex = html.IndexOf("vodCoverUrl");
            int endIndex = html.IndexOf("deviceSubSerail");
            int urlLength = endIndex - startIndex;
            string vodCoverUrl = html.Substring(startIndex, urlLength);
            int perIndex = vodCoverUrl.IndexOf("'") + 1;
            int lastIndex = vodCoverUrl.LastIndexOf("'");
            int truthUrlLength = lastIndex - perIndex;
            string trueURL = vodCoverUrl.Substring(perIndex, truthUrlLength);//摄像头封面图片

            VideoLive model = new VideoLive();
            model.coverImgURL = trueURL;
            model.videoURL = m3u9Url;
            return model;
        }

        /// <summary>
        /// 获取应用管理员发布到视频广场的公共视频资源
        /// </summary>
        /// <param name="backTxt"></param>
        /// <param name="serverTime"></param>
        /// <returns></returns>
        private string SquareVideoListByUser(string backTxt, string serverTime, string appKey, string secret)
        {
            int pageSize_config = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["pageSize"]);
            int pageStart = 0;
            int pageSize = pageSize_config;
            long utk = long.Parse(serverTime); //DateTimeOffset.Now.ToUniversalTime().UtcTicks + "";//时间戳
            //签名源计算字符串
            var jmTxt = "pageSize:" + pageSize + ",pageStart:" + pageStart + ",method:squareVideoListByUser,time:" + utk + ",secret:" + secret;
            string sign = Jiami.GetMD5(jmTxt);
            var dataObj = new
            {
                id = "1",
                method = "squareVideoListByUser",
                @params = new
                {
                    pageSize = pageSize,
                    pageStart = pageStart
                },
                system = new
                {
                    key = appKey,
                    sign = sign,
                    time = utk,
                    ver = "1.0"
                }
            };
            string sendJson = JsonConvert.SerializeObject(dataObj);//发送的json数据
            string url = "https://open.ys7.com/api/method";//接口
            backTxt = RequestWebAPI(url, sendJson);
            return backTxt;
        }


        /// <summary>
        /// 获取accessToken
        /// </summary>
        /// <param name="serverTime"></param>
        /// <returns></returns>
        public string GetAccessToken(string serverTime, string phone, string appKey, string secret)
        {
            long utk = long.Parse(serverTime);//             
            //签名源计算字符串
            var jmTxt = "phone:" + phone + ",method:token/getAccessToken,time:" + utk + ",secret:" + secret;
            string sign = Jiami.GetMD5(jmTxt);
            var dataObj = new
            {
                id = "1",
                method = "token/getAccessToken",
                @params = new
                {
                    phone = phone
                },
                system = new
                {
                    key = appKey,
                    sign = sign,
                    time = utk,
                    ver = "1.0"
                }
            };
            string sendJson = JsonConvert.SerializeObject(dataObj);//发送的json数据
            string url = "https://open.ys7.com/api/method";//接口
            string backTxt = RequestWebAPI(url, sendJson);
            return backTxt;
        }


        /// <summary>
        /// 发送请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="sendData">参数</param>
        /// <returns></returns>
        public string RequestWebAPI(string url, string sendData)
        {
            string backMsg = "";
            try
            {
                System.Net.HttpWebRequest httpRquest = System.Net.HttpWebRequest.CreateHttp(url);
                httpRquest.Method = "POST";
                //httpRquest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
                System.IO.Stream requestStream = httpRquest.GetRequestStream();
                if (string.IsNullOrWhiteSpace(sendData) == false)
                {
                    byte[] dataArray = System.Text.Encoding.UTF8.GetBytes(sendData);
                    requestStream.Write(dataArray, 0, dataArray.Length);
                }
                System.Net.WebResponse response = httpRquest.GetResponse();
                System.IO.Stream responseStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, System.Text.Encoding.UTF8);
                backMsg = reader.ReadToEnd();

                reader.Close();
                reader.Dispose();

                requestStream.Close();
                requestStream.Dispose();
                responseStream.Close();
                responseStream.Dispose();
            }
            catch (Exception)
            {
                throw;
            }
            return backMsg;
        }


    }
}